import legacy from "@vitejs/plugin-legacy";
import { visualizer } from "rollup-plugin-visualizer";
import { defineConfig, loadEnv } from "vite";
import path from "path";
import createVitePlugins from "./vite/plugins";
import postCssPxToRem from "postcss-pxtorem";
import {decryptionPreprocessing} from "./src/utils/aesModeCbc";
// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd());
  const {
    VITE_PORT,
    VITE_HOST,
    VITE_STATIC_BASE_URI,
    VITE_LEGACY_OFF,
    VITE_VISUALIZER_ON,
    VITE_BUILD_DIST,
  } = env;
  const plugins = [createVitePlugins(env, command === "build")];
  const legacyPluginOn = !VITE_LEGACY_OFF || VITE_LEGACY_OFF !== "true";

  if (legacyPluginOn) {
    plugins.push(
      legacy({
        renderLegacyChunks: true,
        targets: ["chrome 49"],
        additionalLegacyPolyfills: ["regenerator-runtime/runtime"], // 面向IE11时需要此插件
      }),
    );
  }
  if (VITE_VISUALIZER_ON && VITE_VISUALIZER_ON !== "false") {
    // 将 visualizer 插件放到最后的位置
    plugins.push(visualizer());
  }
  return {
    // 部署生产环境和开发环境下的URL。
    // 默认情况下，vite 会假设你的应用是被部署在一个域名的根路径上
    // 例如 https://www.xxx.com/。
    // 如果应用被部署在一个子路径上，需要指定子路径(在.env文件中配置)。
    // 例如，如果你的应用被部署在 https://www.xxx.com/prod/，则设置 VITE_STATIC_BASE_URI='/prod/'。
    base: VITE_STATIC_BASE_URI || "",
    build: {
      outDir: VITE_BUILD_DIST || "./dist",
    },
    plugins: plugins,
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: {
        // 设置路径
        "~": path.resolve(__dirname, "./"),
        // 设置别名
        "@": path.resolve(__dirname, "./src"),
      },
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    },
    // vite 相关配置
    server: {
      port: VITE_PORT || 80,
      host: decryptionPreprocessing(VITE_HOST) || true,
      open: false,
    },

    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: "internal:charset-removal",
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === "charset") {
                  atRule.remove();
                }
              },
            },
          },
          postCssPxToRem({
            rootValue: 192, // 1rem，根据 设计稿宽度/10 进行设置
            propList: ["*"], // 需要转换的属性，这里选择全部都进行转换
          }),
        ],
      },
    },
  };
});
